import Vue from 'vue'
import router from '@router'
import Api from '@api'
import Store from '@store'
router.beforeEach((to, from, next) => {
  const $vue = new Vue()
  let data = {
    token: $vue.getToken()
  }
  let methods = {
    /**
     * @purpose 获取token
     */
    getToken (next) {
      let auto = setTimeout(() => {
        $vue.showLoading()
      }, 2000)
      Api.sign
        .token('', data.token)
        .then(r => {
          $vue.closeLoading()
          clearTimeout(auto)
          if (typeof r.data.status !== 'undefined' && r.data.status === 10000) {
            $vue.setToken(r.data.token)
            Store.dispatch('getUserInfo', (r) => {
              next({replace: true})
            })
          } else {
            $vue.removeToken()
            next()
          }
        })
    }
  }
  if (from.path === '/') {
    if (data.token) {
      methods.getToken(next)
    } else {
      next()
    }
  } else {
    next()
  }
})
